package com.sos.config;

import com.sos.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    
    private final JwtUtils jwtUtils;
    
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                                  WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpServletRequest = servletRequest.getServletRequest();
            
            // 从请求参数中获取token
            String token = httpServletRequest.getParameter("token");
            log.info("WebSocket握手，从getParameter获取token: {}", token);
            
            // 尝试从查询字符串中获取token
            String queryString = httpServletRequest.getQueryString();
            log.info("WebSocket握手，查询字符串: {}", queryString);
            
            if (token == null && queryString != null && queryString.contains("token=")) {
                // 手动解析查询字符串
                String[] params = queryString.split("&");
                for (String param : params) {
                    if (param.startsWith("token=")) {
                        token = param.substring(6);
                        log.info("WebSocket握手，从查询字符串解析token: {}", token);
                        break;
                    }
                }
            }
            
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                log.info("WebSocket握手，去除Bearer前缀后token: {}", token);
            }
            
            if (token != null && jwtUtils.isTokenValid(token)) {
                String username = jwtUtils.getUsernameFromToken(token);
                attributes.put("username", username);
                attributes.put("token", token);
                log.info("WebSocket握手成功，用户: {}", username);
                return true;
            } else {
                log.warn("WebSocket握手失败，无效的token，token={}", token);
            }
        } else {
            log.warn("WebSocket握手失败，请求不是ServletServerHttpRequest类型");
        }
        
        return false;
    }
    
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                              WebSocketHandler wsHandler, Exception exception) {
        // 握手后处理
    }
}